package com.example.blog.controller;

import com.example.blog.entity.User;
import com.example.blog.entity.Article;

import com.example.blog.repository.ArticleRepository;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Controller
@RequestMapping("/publish")
public class UserCtl {

    @Autowired
    private ArticleRepository articleRepository; // 注入 ArticleRepository
    @PostMapping(value = "users")
    public String Show(){
        return "redirect:/login/users";
    }
    @PostMapping
    public String publishArticle(@RequestParam String title,
                                 @RequestParam String content,
                                 @RequestParam String tagName,
                                 HttpSession session) {
        User user = (User) session.getAttribute("user");

        if (user != null) {

            Article article = new Article();
            article.setUser_id(user.getId());
            article.setTitle(title);
            article.setContent(content);
            article.setTagName(tagName);
            article.setUsername(user.getName());
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String formattedDateTime = LocalDateTime.now().format(formatter);
            article.setUpdatetime(formattedDateTime);
            // 假设你有一个方法来设置更新时间和点赞数
            articleRepository.save(article);
          // 直接使用 ArticleRepository 的 save 方法
            return "redirect:/login/users";
        } else {
            return "login";
        }
    }




}